from django import forms
from django.utils import timezone

from .models import BlogPost


class BlogPostForm(forms.ModelForm):
    """Form definition for BlogPost."""

    def __init__(self, *args, **kwargs):
        print(kwargs)
        self.author = (kwargs.pop('author', None) or kwargs['instance'].author)
        super().__init__(*args, **kwargs)

    def clean_title(self):
        title = self.cleaned_data['title']
        qs = BlogPost.objects.filter(author=self.author, title=title)
        print(self.instance.title)
        if self.instance and self.instance.title == title:
            qs = qs.exclude(title=title)
        if qs.exists():
            raise forms.ValidationError(
                "You have already written a book with same title.")
        return title

    def clean_published_at(self):
        published_at = self.cleaned_data['published_at']
        is_published = self.cleaned_data['is_published']
        if is_published:
            if published_at is not None:
                return published_at
            else:
                return timezone.now()
        else:
            return None


    class Meta:
        """Meta definition for BlogPostform."""

        model = BlogPost
        fields = (
            'title',
            'slug',
            'content',
            'is_published',
            'published_at',
        )
